using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Reflection;
using System.Deployment.Application;
using System.Net;
using System.Threading;
using System.Net.Sockets;


namespace Launcher
{
    public partial class LauncherForm : Form
    {
        private string WowPath;
        private string txtfolderPath;
        private string versionfilewow;
        private int dwpatchurl;
        private string regeditpath;
        private string relmw;
        string[,] patchver = {                 
{"3, 0, 1, 8874", "http://royaume-eternity.com/download_wow/patch/WoW-3.0.1.8874-to-3.0.2.9056-frFR-patch.exe"},
{"3, 0, 2, 9056","http://royaume-eternity.com/download_wow/patch/WoW-3.0.2.9056-to-3.0.3.9183-frFR-patch.exe"},
{"3, 0, 3, 9183","http://weeb.ch/WoW-3.0.3.9183-to-3.0.8.9464-frFR-patch.exe"},
{"3, 0, 8, 9464","http://weeb.ch/WoW-3.0.8.9464-to-3.0.8.9506-frFR-patch.exe"},
{"3, 0, 8, 9506","http://weeb.ch/WoW-3.0.8.9506-to-3.0.9.9551-frFR-patch.exe"},
{"3, 0, 9, 9551","http://weeb.ch/WoW-3.0.9-to-3.1.0-frFR-Win-patch.exe"},     
{"3, 1, 0, 9767","http://weeb.ch/WoW-3.1.0.9767-to-3.1.1.9806-frFR-patch.exe"},
{"3, 1, 1, 9806","http://weeb.ch/WoW-3.1.1.9806-to-3.1.1.9835-frFR-patch.exe"},
{"3, 1, 1, 9835","http://weeb.ch/WoW-3.1.1.9835-to-3.1.2.9901-frFR-patch.exe"},
{"3, 1, 2, 9901","http://weeb.ch/WoW-3.1.2.9901-to-3.1.3.9947-frFR-patch.exe"}, 
{"3, 1, 3, 9947","http://z.ziwee.fr/patch/wow-3.1.3.9947frFR.exe"},
{"3, 2, 0, 10192","http://z.ziwee.fr/patch/wow-3.1.3.9947frFR.exe"}, 
{"3, 2, 0, 10314","http://dl.free.fr/jbucfdyPN/wow-3.2.0.10314frFR.exe"},
{"3, 2, 2, 10482","http://dl.free.fr/pidKTDp5K/wow-3.2.2.10482frFR.exe"}};




        public LauncherForm()
        { InitializeComponent(); BWSiteNews.RunWorkerAsync(); BWTwitter.RunWorkerAsync();}
        protected override void OnLoad(EventArgs e)
        {

            base.OnLoad(e);

            // détermine si l'application a été déployée.
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
            {
                // si oui, récupération de la version
                this.Text = string.Format("{0} ({1})", this.Text, ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString());
            }
            else
            {
                this.Text = string.Concat(this.Text, " (Pas de déploiement réseau)");
            }


        }
        private void LauncherForm_Load(object sender, EventArgs e)
        {
            //****************************************************** 64 bits and 32 bits test **************************************************************
            regeditpath = "Software\\LauncherOW";

            RegistryKey Key = Registry.CurrentUser.OpenSubKey(@regeditpath, false);
            if (Key != null)
            {
                WowPath = Key.GetValue("InstallPath").ToString();
                string wowexe = WowPath + "wow.exe";
                System.Diagnostics.FileVersionInfo fileVersInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(wowexe);
                Verlabel.Text = "Version : " + (fileVersInfo.FileVersion);
                string versionnow = "3, 2, 2, 10505";
                versionfilewow = fileVersInfo.FileVersion;
                relmw = WowPath + "Data\\frFR\\realmlist.wtf";
                for (int i = 0; i < 14; i++)
                {
                    if (patchver[i, 0].Equals(versionfilewow))
                    { dwpatchurl = i; break; }
                }


                if (versionfilewow == versionnow) { ErrorBox.Visible = false; }

                else
                {
                    this.BackgroundImage = global::Launcher.Properties.Resources.BGwar;
                    ErrorBox.Visible = true; SiteNewsBrowser.Visible = false; Cachelink.Visible = false; Chatlink.Visible = false;
                    dwlabel.Visible = true; PvPlink.Visible = false; MajLink.Visible = false; Servercheck.Visible = false; ProgBar.Visible = true;
                    Votelink.Visible = false; Forumlink.Visible = false; Boutiquelink.Visible = false; Verlabel.Visible = false; Play.Visible = false;
                    ErrorBox.Text = "Votre version n'est pas compatible avec le serveur, veuillez donc procédez a la mise à jour " + patchver[dwpatchurl + 1, 0] + " car, vous avez actuellement la version " + versionfilewow;
                    dwlabel.Text = "[Téléchargement en cours]";
                    //dwlabel.Text = dwpatchurl.ToString() + "*********" + WowPath + "*********" + versionfilewow;
                    DWFiles.RunWorkerAsync();

                }
            }
            else
            {   this.BackgroundImage = global::Launcher.Properties.Resources.BGwar;
                ErrorBox.Visible = true; SiteNewsBrowser.Visible = false; Cachelink.Visible = false;
                PvPlink.Visible = false; MajLink.Visible = false; Servercheck.Visible = false; Chatlink.Visible = false;
                Votelink.Visible = false; Forumlink.Visible = false; Boutiquelink.Visible = false; Verlabel.Visible = false; Play.Visible = false;
                Folderlabel.Visible = true; ErrorBox.Text = "Assistance Open-WoW Launcher vous demande de définir le répertoire du jeu World of Warcaft en cliquant sur le lien ci-dessous !";
            }
          
            //******************************************************Fin 64 bits and 32bits **************************************************************

 

        }

        




        private void Play_Click_1(object sender, EventArgs e)
        {
            RegistryKey Key = Registry.CurrentUser.OpenSubKey(@regeditpath, false);
            if (Key != null) { WowPath = Key.GetValue("InstallPath").ToString(); }
            string wowexe = WowPath + "wow.exe";
            System.Diagnostics.Process.Start(@wowexe); Application.Exit();
        }
        private void Play_MouseDown_1(object sender, MouseEventArgs e)
        { this.Play.BackgroundImage = Launcher.Properties.Resources.B1press; }
        private void Play_MouseUp_1(object sender, MouseEventArgs e)
        {
            this.Play.BackgroundImage = Launcher.Properties.Resources.B1over;
        }
        private void Play_MouseLeave_1(object sender, System.EventArgs e)
        {
            this.Play.BackgroundImage = Launcher.Properties.Resources.B1;
        }
        private void Play_MouseHover(object sender, EventArgs e)
        {
            this.Play.BackgroundImage = Launcher.Properties.Resources.B1over;
        }
        private void Cachelink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string doseff = WowPath + "Cache";
            if (System.IO.Directory.Exists(@doseff))
            {
                System.IO.Directory.Delete(@doseff, true);
                MessageBox.Show("Cache supprimé", "Supprimé !", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            else
            {
                MessageBox.Show("Cache déjà supprimé !", "Supprimé !", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void Chatlink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Form2 frm = new Form2();
            frm.Show();
        }
        private void Servercheck_CheckedChanged(object sender, EventArgs e)
        {
            if (Servercheck.Checked)
            { StreamWriter realmlist = new StreamWriter(@relmw); realmlist.Write("set realmlist eu.logon.worldofwarcraft.com set patchlist eu.version.worldofwarcraft.com set portal eu"); realmlist.Close(); }
            else { StreamWriter realmlist = new StreamWriter(@relmw); realmlist.Write("set realmlist logon.open-wow.net set patchlist eu.version.worldofwarcraft.com set portal eu"); realmlist.Close(); }


        }
        private void Boutiquelink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.open-wow.net/shop.php");
        }
        private void Votelink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.open-wow.net/vote");
        }
        private void PvPlink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.open-wow.net/top50.php");
        }
        private void Forumlink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.open-wow.net/forum/");
        }
        private void MajLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ErrorBox.Visible = true; Closelabel.Visible = true; SiteNewsBrowser.Visible = false;
            ErrorBox.Text = ("MaJ XX dec 2009 rev XX \n Methode de mise a jours revue ! \n\n\n MaJ 20 dec 2009 rev 11 & 12 \n -Changement de la taille du cadre News \n -Changement du logo et de l'icon d'open-wow \n -Correction des fautes d'orthographes \n Correction du bug du au realmlist \n\n\n MaJ 18 dec 2009 rev 7 a 10 \n -Changement des ressources Ico, Logo Open-wow et Play (remerci 'dessan')  \n\n\n MaJ 17 dec 2009 rev 5 & 6 \n -Correction du crach possible du a un manque du répertoire W o W \n -Correction de crash possible des versions 32 et 64bits \n -Préférence le choix entre jouer sur priver ou officiel ! \n -Supprimer Taux xp et Taux honneur useless \n -Ajout de la version Launcher bar titre \n -Ajout du mouse hover Play (merci 'dessan' pour l'image)");
        }
        private void Folderlabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@regeditpath, false);
            if (key == null)
            {
                if (FolderBox.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    key = Registry.CurrentUser.CreateSubKey(@regeditpath);
                    txtfolderPath = FolderBox.SelectedPath.ToString() + "\\";
                    string txtfolderPathwow = txtfolderPath + "Launcher.exe";
                    key.SetValue("InstallPath", txtfolderPath);
                    key.SetValue("GamePath", txtfolderPathwow);
                    key.Close();
                    MessageBox.Show("Attention, l'application va ce fermer !", "Fermer", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Application.Exit();
                }
            }
        }
        private void BWSiteNews_DoWork(object sender, DoWorkEventArgs e)
        {
            SiteNewsBrowser.Navigate("http://www.ziwee.fr/OpenWoW/OpenWoW.php");
        }
        private void BWTwitter_DoWork(object sender, DoWorkEventArgs e)
        {
            Twitterbrowser.Navigate("http://www.ziwee.fr/OpenWoW/OpenWoW.php?p=twitter");
        }
        private void DWFiles_DoWork(object sender, DoWorkEventArgs e)
        {
            // the URL to download the file from
            string sUrlToReadFileFrom = patchver[dwpatchurl, 1];
            //Files name 
            string FileName2 = sUrlToReadFileFrom.Substring(sUrlToReadFileFrom.LastIndexOf("/") + 1);
            // the path to write the file to
            string sFilePathToWriteFileTo = WowPath + FileName2 + ".exe";
            // first, we need to get the exact size (in bytes) of the file we are downloading
            Uri url = new Uri(sUrlToReadFileFrom);
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            response.Close();

            // gets the size of the file in bytes
            Int64 iSize = response.ContentLength;
            // keeps track of the total bytes downloaded so we can update the progress bar
            Int64 iRunningByteTotal = 0;
            // use the webclient object to download the file
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                // open the file at the remote URL for reading
                using (System.IO.Stream streamRemote = client.OpenRead(new Uri(sUrlToReadFileFrom)))
                {
                    // using the FileStream object, we can write the downloaded bytes to the file system
                    using (Stream streamLocal = new FileStream(sFilePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        // loop the stream and get the file into the byte buffer
                        int iByteSize = 0;
                        byte[] byteBuffer = new byte[iSize];
                        while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                        {
                            // write the bytes to the file system at the file path specified
                            streamLocal.Write(byteBuffer, 0, iByteSize);
                            iRunningByteTotal += iByteSize;
                            // calculate the progress out of a base "100"
                            double dIndex = (double)(iRunningByteTotal);
                            double dTotal = (double)byteBuffer.Length;
                            double dProgressPercentage = (dIndex / dTotal);
                            int iProgressPercentage = (int)(dProgressPercentage * 100);
                            // update the progress bar
                            DWFiles.ReportProgress(iProgressPercentage);
                        }
                        // clean up the file stream
                        streamLocal.Close();
                    }
                    // close the connection to the remote server
                    streamRemote.Close();
                }
            }
        }
        private void DWFiles_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            string progrtxt = e.ProgressPercentage.ToString();
            ProgBar.Value = e.ProgressPercentage;
            dwlabel.Text = "Téléchargé " + progrtxt + "%";
        }
        private void DWFiles_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // the URL to download the file from
            string sUrlToReadFileFrom = patchver[dwpatchurl, 1];
            string FileName2 = sUrlToReadFileFrom.Substring(sUrlToReadFileFrom.LastIndexOf("/") + 1);
            string sFilePathToWriteFileTo = WowPath + FileName2 + ".exe";
            ProcessStartInfo pInfo = new ProcessStartInfo();
            //Set the file name member of the process info structure.
            pInfo.FileName = @sFilePathToWriteFileTo;
            Process p = Process.Start(pInfo);
            p.WaitForInputIdle();
            p.WaitForExit();
            MessageBox.Show("Toujours en attend du code !");
            Process[] procs = Process.GetProcessesByName("Launcher");
            foreach (Process proc in procs)
            { proc.Kill(); }
            Application.Exit();

        }
        private void Closelabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ErrorBox.Visible = false; Closelabel.Visible = false; SiteNewsBrowser.Visible = true;
        }

    }}
